package com.ybear.ybnetworkutil.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.ybear.ybnetworkutil.annotations.NetworkType;

import static android.net.NetworkInfo.State.CONNECTED;

/**
 * 网络状态改变广播
 */
class NetworkChangReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        NetworkInfo info;
        boolean isAvailable;
        //监听网络状态
        if( ConnectivityManager.CONNECTIVITY_ACTION.equals( action ) ) {
            info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if( info == null ) { return; }
            //网络是否在线
            isAvailable = info.getState() == CONNECTED && info.isAvailable();
            //处理状态
            doChange(info.getType(), isAvailable);
        }
    }

    /**
     * 处理状态
     * @param type          网络类型
     * @param isAvailable   网络是否在线
     */
    private void doChange(int type, boolean isAvailable) {
        NetworkChangeManage ncm = NetworkChangeManage.get();
        //当前网络类型 - 未知
        String networkType = NetworkType.UNKNOWN;
        switch ( type ) {
            case ConnectivityManager.TYPE_MOBILE:
                //网络类型 - 移动网络
                networkType = NetworkType.MOBILE;
                break;
            case ConnectivityManager.TYPE_WIFI:
                //网络类型 - 无线网络
                networkType = NetworkType.WIFI;
                break;
        }
        //网络类型 - 无网络
        if( !isAvailable ) networkType = NetworkType.NONE;
        //回调网络状态
        ncm.callbackNetworkChange( isAvailable, networkType );
    }
}
